/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client;
import Asterix21.CAsterix21;
import Buffer.Flight;
import Buffer.FlightData;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Vika
 */
public class ClientThread implements Runnable{
	
	//Atributes
	private boolean KeepConnect;
	private CAsterix21 Asterix21 = new CAsterix21();
        private DataInputStream InputStream;
	private FlightData FlightData;
	private int Port;
	private int BufferLen;
	private short[] DataBuffer = new short[1024];
	private Socket ClientSocket;
	private String Host;
	
	//Constructor
	public ClientThread(int port, String host, FlightData flightdata)
	{
            this.Port = port;
            this.Host = host;
            this.FlightData = flightdata;
	}

   
	//Methods
	public boolean Connect()
	{
            boolean isConnect = false;

            if (KeepConnect)
            {
                isConnect = true;
            }
            else
            {
                try
                {
                    ClientSocket = new Socket (Host, Port);
                    InputStream = new DataInputStream (ClientSocket.getInputStream());
                    isConnect = true;
                }
                catch (SocketException e)
                {
                    System.err.println("Socket error : " + e);
                }
                catch (UnknownHostException e)
                {
                    System.err.println("Invalid host.");
                }
                catch (IOException e)
                {
                    System.err.println ("I/O error : " + e);
                }
            }

            KeepConnect = isConnect;
            return (isConnect);
	}
	
	//Close Connection
	private void Close() throws IOException
	{
            if (KeepConnect)
            {
                ClientSocket.close();
                KeepConnect = false;
            }
            else
            {
                System.out.println("No Connection.");
            }
	}
	
	//Get Data from server
	private boolean getData()
	{
            boolean Success = false;
            int i = 0;
            short data, octetHigh, octetLow;

            if (KeepConnect)
            {
                try
                {
                    do
                    {
                        data = InputStream.readByte();
                        data = (short) (data & 0x00FF);
                    }
                    while (data != (short) 0x0015);

                    DataBuffer[i++] = data;
                    octetHigh = InputStream.readByte();
                    DataBuffer[i++] = (short) (octetHigh & 0x00FF);
                    octetLow = InputStream.readByte();
                    DataBuffer[i++] = (short) (octetLow & 0x00FF);
                    BufferLen = 256 * octetHigh + octetLow;

                    while (i < BufferLen)
                    {
                        DataBuffer[i++] = (short) ((InputStream.readByte()) & 0x00FF);
                    }

                    Success = true;
                }
                catch (IOException e)
                {
                    System.err.println("I/O error get data : " + e);
                }
            }
            else
            {
                System.out.println("No connection to get data.");
            }

            return (Success);
	}
	
	public void run()
	{
            
            boolean threadExit = false;

            System.out.println("thread client started..");
            while (!threadExit)
            {
                try
                {
                    if (getData())		//get data from server and put in on DataBuffer
                    {
                        //Parsing DataBuffer with asterix21 class
                        Asterix21.IsiData(DataBuffer, BufferLen);
                        Asterix21.ProsesDataAsterix21();

                        //Synchronize
                        synchronized (FlightData)
                        {
                        try {
                            FlightData.addData(
                                Asterix21.m_strTargetAddress,
                                Asterix21.m_sTargetID,
                                Asterix21.m_strCountry,
                                Asterix21.m_iAltitude,
                                Asterix21.m_fGroundSpeed,
                                Asterix21.m_fTrackAngle,
                                Asterix21.m_fBarometricVerticalRate,
                                Asterix21.m_fLatitudeInWGS,
                                Asterix21.m_fLongitudeInWGS,
                                Asterix21.m_sTimeOfDay
                                );
                        } catch (IOException ex) {
                            Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        }
                    }
                    else
                    {
                        Thread.sleep (100);
                    }
                }
                catch (InterruptedException e)
                {
                    threadExit = true;
                }
            }
            System.out.println("thread client exit..");
            
            try {
                Close();
            } catch (IOException ex) {
                Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
            }
	}

    public static void main(String[] args) {
        //ClientThread ct = new ClientThread(6789, "127.0.0.1");
        //Thread thread = new Thread (ct);
        //thread.start();

        //ct.Connect();
    }
}
